
package com.jiang.droidsms.ui;

import com.jiang.droidsms.R;
import com.jiang.droidsms.data.DroidSMSConfig;
import com.jiang.droidsms.data.SMSTable;
import com.jiang.droidsms.data.SMSTable.CanonicalAddresses;
import com.jiang.droidsms.data.SMSTable.SMS;
import com.jiang.droidsms.data.SMSTable.Threads;
import com.jiang.droidsms.ui.adapter.ThreadListAdapter;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * The Class ThreadsListActivity.
 */
public class ThreadsListActivity extends Activity {

    private BaseAdapter mAdapter;

    private ListView mListView;

    private MediaPlayer mPlayer = new MediaPlayer();

    private AudioManager mAudioManager;

    boolean isHiden = false;

    /*
     * (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // �õ�ϵͳ��AudioManager����
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        setContentView(R.layout.thread_layout);
        // Ϊ��Activityע��۲���

        mListView = (ListView) findViewById(R.id.thread_list);

        // ����ListView�ָ��߸߶�Ϊ0
        mListView.setDividerHeight(0);
        // �϶�ʱ�ı�����ɫ
        mListView.setCacheColorHint(0x00000000);
        // �������б����±�Ե�ĸ߶�Ϊ2������
        mListView.setFadingEdgeLength(5);

        final Cursor cursor = getContentResolver()
                .query(SMSTable.Threads.CONTENT_URI, null, null, null,
                       SMSTable.Threads.DATE + " ASC");
        mAdapter = new ThreadListAdapter(this, cursor);
        mListView.setAdapter(mAdapter);
        mListView
                .setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
                    @Override
                    public void onCreateContextMenu(ContextMenu menu, View v,
                            ContextMenuInfo menuInfo) {
                        // final AdapterContextMenuInfo acmi =
                        // (AdapterContextMenuInfo) menuInfo;
                        final int threadId = cursor.getInt(cursor
                                .getColumnIndex(Threads._ID));

                        MenuItem viewItem = menu.add(R.string.view);
                        viewItem
                                .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                                    @Override
                                    public boolean onMenuItemClick(MenuItem item) {
                                        Intent intent = new Intent(
                                                                   ThreadsListActivity.this,
                                                                   ConversationActivity.class);
                                        intent
                                                .putExtra(
                                                          DroidSMSConfig.EXTRA_THREAD_ID,
                                                          threadId);
                                        startActivity(intent);
                                        return false;
                                    }
                                });
                        MenuItem deleteItem = menu.add(R.string.delete);
                        deleteItem
                                .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                                    @Override
                                    public boolean onMenuItemClick(MenuItem item) {
                                        new Thread(new Runnable() {
                                            public void run() {
                                                ContentResolver cr = ThreadsListActivity.this
                                                        .getContentResolver();
                                                cr.delete(SMS.CONTENT_URI,
                                                          SMS.THREAD_ID + "="
                                                                  + threadId,
                                                          null);
                                                cr.delete(Threads.CONTENT_URI,
                                                          Threads._ID + "="
                                                                  + threadId,
                                                          null);
                                            }
                                        }).start();
                                        return false;
                                    }
                                });
                        MenuItem callItem = menu.add(R.string.call);
                        callItem
                                .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                                    @Override
                                    public boolean onMenuItemClick(MenuItem item) {
                                        Cursor c = getContentResolver()
                                                .query(
                                                       CanonicalAddresses.CONTENT_URI,
                                                       null,
                                                       CanonicalAddresses._ID
                                                               + "="
                                                               + cursor
                                                                       .getInt(cursor
                                                                               .getColumnIndex(Threads.RECIPIENT_IDS)),
                                                       null, null);
                                        try {
                                            c.moveToFirst();
                                            Uri callUri = Uri
                                                    .parse("tel:"
                                                            + c
                                                                    .getString(c
                                                                            .getColumnIndex(CanonicalAddresses.ADDRESS)));
                                            Intent intent = new Intent(
                                                                       Intent.ACTION_CALL,
                                                                       callUri);
                                            startActivity(intent);
                                        } catch (Exception e) {
                                            Toast
                                                    .makeText(
                                                              ThreadsListActivity.this,
                                                              "�绰��������",
                                                              Toast.LENGTH_LONG)
                                                    .show();
                                        } finally {
                                            c.close();
                                        }
                                        return false;
                                    }
                                });
                    }
                });

        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(final AdapterView<?> parent,
                    final View view, final int position, long id) {
                Intent intent = new Intent(ThreadsListActivity.this,
                                           ConversationActivity.class);
                intent.putExtra(DroidSMSConfig.EXTRA_THREAD_ID, cursor
                        .getInt(cursor.getColumnIndex(Threads._ID)));
                startActivity(intent);
            }
        });
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (isHiden) {
                        Intent intent = new Intent(ThreadsListActivity.this,
                                                   NotificationActivity.class);
                        startActivity(intent);
                    } else {
                        mAdapter.notifyDataSetChanged();
                    }
                    // vibrate();
                    // playSound();
                    break;
                case 1:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    public void playSound() {
        try {
            // �õ�Ĭ�����������
            int current = mAudioManager
                    .getStreamVolume(AudioManager.STREAM_ALARM);
            mPlayer.reset();
            // �õ�֪ͨ��
            mPlayer.setDataSource(this, RingtoneManager
                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            mPlayer.setVolume(current, current);
            mPlayer.prepare();
            mPlayer.start();
        } catch (Exception e) {
        }
    }

    public void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        // ����ʾ
        vibrator.vibrate(1000);
    }

    @Override
    protected void onRestart() {
        isHiden = false;
        mAdapter.notifyDataSetChanged();
        super.onRestart();
    }

    @Override
    protected void onDestroy() {
        isHiden = true;
        super.onDestroy();
    }

    public class Receiver extends BroadcastReceiver {
        public static final String ACTION_UPDATE_LIST = "update_list";

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() == ACTION_UPDATE_LIST) {
                mAdapter.notifyDataSetChanged();
            }
        }
    }
}
